#include <iostream>
using namespace std;

#include <sys/socket.h>

#include <XrddmConfig.h>

#ifdef HAS_APPMON
#include <ApMon.h>
/* the next two lines are necessary for using the logging facility */
#include "utils.h"
using namespace apmon_utils;
#endif

void printHelp();
#ifdef HAS_APPMON
bool testAppMon();
#endif
int main(int argc, char **argv)
{
//   char *destList[1] = {(char*)"http://alicepc100.jinr.ru/gentoo-files/monalisa_cern.conf"};
  char *destList[1] = {(char*)"http://alicepc100.jinr.ru/gentoo-files/monalisa_saske.conf"};
  ApMon *fAppMon = 0;
  const char* message = "Hello";
  double val = 1;
  char logmsg[100];
  char jobname[100];
  char farmname[100] = {"XrdDownloadManager"};

  // Part 1 (optional) get the name that is to be looked up
  char hostname[100];
  gethostname(hostname, 100);

  // Part 2 (required)
  hostent * record = gethostbyname(hostname);
  if (record == NULL) {
    herror("gethostbyname failed");
    exit(1);
  }

  sprintf(jobname, "%s_%d", record->h_name, getpid());
  logger(INFO, jobname);
  sprintf(logmsg, "Official name: %s_%d\n", record->h_name, getpid());
  logger(INFO, logmsg);

  try {
    fAppMon = new ApMon(1, destList);
    fAppMon->setRecheckInterval(300);

    try {
//       fAppMon->sendParameter((char *)"XRDDM", NULL, (char *)"my_parameter", XDR_REAL64, (char *) message);
//       fAppMon->sendParameter((char *)"XRDDM", NULL, (char *)"my_parameter", XDR_REAL64, (char *) message);
      for (int i = 0;i < 1000;i++) {
        val = i;

        sprintf(logmsg, "Sending %lf to %s with name %s\n", val,farmname, jobname);
        logger(INFO, logmsg);


        fAppMon->sendParameter(farmname, jobname , (char*)"Status", 1);
        fAppMon->sendParameter(farmname, jobname , (char*)"Message", (char*)"My Message");
        fAppMon->sendParameter(farmname, jobname , (char*)"from", XDR_REAL64, (char *)&val);
        fAppMon->sendParameter(farmname, jobname , (char*)"to", XDR_REAL64, (char *)&val);

        sleep(10);
      }

    }
    catch (runtime_error &e) {
      logger(WARNING, e.what());
    }

  }
  catch (runtime_error &e) {
    logger(WARNING, e.what());
  }
}

void printHelp() {}

#ifdef HAS_APPMON
bool testAppMon()
{
  cout << "Testing Appmon ..." << endl;
  return true;
}
#endif
